# -*- coding: utf-8 -*-
import datetime
import logging
import time
import urllib

from google.appengine.ext import db
from google.appengine.ext import webapp
from Weibo.WeiboManage import updateWeibo, A3replay, doShouQuan
from methods import checkUser, replaceChar
from regUserInit import addInitReplay
from google.appengine.api import urlfetch
import subscribe
from models import Images
from photoLib import PhotoLib
from subscribe import SubscribeOther, findSubscribeOthers
############################################################
class ContentClass(db.Model):       #普通内容主表（包含级别和内容）
    author = db.UserProperty()        #无效，可以去除
    maincode  = db.StringProperty(multiline=True) #存第一级内容编号，后面的表都加上  
    code = db.StringProperty(multiline=True)      #编码（手工编码）
    content = db.TextProperty()   #内容
    title = db.StringProperty(multiline=True)   #抬头标题
    father = db.StringProperty(multiline=True)    #//父级内容编码，当父级为空时level为0
    level= db.StringProperty(multiline=True)      #//级别 从上到下分别0、1-5，level为0是唯一
    lastUpdateTime = db.DateTimeProperty(auto_now_add=True)  #//上次更新时间
    updateSpanTime = db.StringProperty(multiline=True)  #//更新间隔时间
    status = db.StringProperty(multiline=True)       #//状态
    #previous =db.StringProperty(multiline=True)  #//前一个编号,如是第一个则为-1
    #date = db.DateTimeProperty(auto_now_add=True)    #//发布时间
  
class ReplyContent(db.Model):       #//需回复的内容表（调查等需要用户回复的内容）
    author = db.UserProperty()        #//无效，可以去除
    maincode  = db.StringProperty(multiline=True) #存第一级内容编号，后面的表都加上  
    code = db.StringProperty(multiline=True)    #//编码（手工编码）
    content = db.TextProperty() #//内容
    father = db.StringProperty(multiline=True)  #//父级内容编码
    level= db.StringProperty(multiline=True)    #//级别 从上到下分别1-5
    replyType = db.StringProperty(multiline=True) #//回复类别 1：文本回复  2、单选选择回复 3、多选选择回复
    status = db.StringProperty(multiline=True)       #//状态
    lastUpdateTime = db.DateTimeProperty(auto_now_add=True)#//上次更新时间
    #date = db.DateTimeProperty(auto_now_add=True)#//发布时间
  
class Subscribe(db.Model):  #//用户订阅表,第一层数据
#    author = db.UserProperty() #//无效去除
    userName = db.StringProperty(multiline=True)#//订阅人
    maincode  = db.StringProperty(multiline=True) #存第一级内容编号，后面的表都加上  
    #contentCode = db.StringProperty(multiline=True)#//订阅内容编号
    subscribeType = db.StringProperty(multiline=True)#//0 表示下面的全要。1 表示下面的另外订阅说明。
    lastUpdateTime = db.DateTimeProperty(auto_now_add=True) #//上次更新时间。
    status=db.StringProperty(multiline=True) #//0 取消订阅了，还没真正物理删除。1 订阅
#    DownLastUpdateTime=db.DateTimeProperty(auto_now_add=True) #//订阅改变时间
    #date = db.DateTimeProperty(auto_now_add=True)  #//订阅时间

  
class Photo(db.Model): #//图片表
    author = db.UserProperty()#//无效去除
    photoCode = db.StringProperty(multiline=True)#//图片编码
    photoFile = db.StringProperty(multiline=True)#//图片文件
    photoFile_Small = db.StringProperty(multiline=True)#//图片缩略图片
    #date = db.DateTimeProperty(auto_now_add=True)#//图片生成时间

class User(db.Model): #//用户表 
#    author = db.UserProperty() #//无效去除
    userName = db.StringProperty(multiline=True) #//用户名
    passWord = db.StringProperty(multiline=True)  #//密码
    trueName = db.StringProperty(multiline=True)  #//姓名
    tele = db.StringProperty(multiline=True)      #//电话号码
    mobile = db.StringProperty(multiline=True)    #//手机
    date = db.DateTimeProperty(auto_now_add=True)  #//注册时间
    lastUpdateTime = db.StringProperty(multiline=True) #//无效数据列

class Reply(db.Model): #//用户回复表
#    author = db.UserProperty()#/无效去除
    userName = db.StringProperty(multiline=True)#//用户名
    maincode  = db.StringProperty(multiline=True) #存第一级内容编号，后面的表都加上
    code = db.StringProperty(multiline=True)#//所回复的内容编码
    replyContent = db.StringProperty(multiline=True)#//回复内容
    replyType = db.StringProperty(multiline=True)#//回复类型
    replyTime = db.DateTimeProperty(auto_now_add=True)#//回复时间
    #date = db.DateTimeProperty(auto_now_add=True) #//无效去除

class PhotoLib_Photo(db.Model):#//图库包含图片表
    indexNo = db.IntegerProperty()#//图片排序号
    photoLibCode = db.StringProperty(multiline=True)#//图库编号
    photoCode = db.StringProperty(multiline=True)#//图片编号
    status =db.StringProperty(multiline=True) #//图片状态 1=改变图片名字、2=已删、3=增加
    lastUpdateTime = db.DateTimeProperty(auto_now_add=True)#//上次更新时间

class User_PhotoLib(db.Model): #//用户订阅图库表
    userName = db.StringProperty(multiline=True) #//用户名
    photoLibCode = db.StringProperty(multiline=True)#//图库编号
    photoLibType = db.StringProperty(multiline=True)#//图库类型
    lastUpdateTime = db.DateTimeProperty(auto_now_add=True)#//上次更新时间


#用户登录接口
class UserLogin(webapp.RequestHandler):
    def get(self):
        UserName = self.request.get('UserName')
        UserPwd = self.request.get('UserPwd')
        success = '0'
        errorName='2'
        greetings = db.GqlQuery("SELECT * FROM User where userName=:1 and passWord=:2",UserName,UserPwd)
        for greeting in greetings:
            success ='1'
        if success=='1':
            self.response.out.write('%s'%success)
        else:
            greetings= db.GqlQuery("SELECT * FROM User where userName=:1",UserName)
            for greeting in greetings:
                errorName='3'
            if errorName=='3':
                self.response.out.write('%s'%errorName)
            else:
                self.response.out.write('%s'%errorName)

#用户注册接口
class UserRegister(webapp.RequestHandler):
    def get(self):
        try:
            UserName = self.request.get('UserName')
            UserPwd = self.request.get('UserPwd')
            userExist = '0'
            try:
                int(UserName)
                int(UserPwd)
            except :
                self.response.out.write('2')
                return
            #没有进行参数正确验证
            if UserName=='' or UserPwd=='':
                self.response.out.write('2')
                return
            greetings = db.GqlQuery("SELECT * "
                                    "FROM User "
                                    "where userName=:1 ",UserName)
            for greeting in greetings:
                userExist ='1'
            if userExist=='1':
                self.response.out.write('2')
            else:
                greeting = User()
                greeting.userName = self.request.get('UserName')
                greeting.passWord = self.request.get('UserPwd')
                greeting.trueName = self.request.get('trueName')
                greeting.tele = self.request.get('tele')
                greeting.mobile = self.request.get('mobile')
                greeting.date = getCurrentTime()
                greeting.put()
                addInitReplay(greeting.userName,greeting.trueName,greeting.tele,greeting.mobile)#默认初始化订阅
                self.response.out.write('1')
        except:
            self.response.out.write('2')

def doRePassWord(self):
    pas=[]
    for p in self.request.get('Content').split('**'):
        if p:
            pas.append(p)
    if len(pas)==3 and pas[1]==pas[2]:
        u=db.GqlQuery("SELECT * FROM User where userName=:1 AND passWord=:2 ",self.request.get('UserName'),pas[0]).fetch(1)
        if len(u)==1:
            u[0].passWord=pas[1]
            u[0].put()
            self.response.out.write('0')
            return
        else:
            self.response.out.write('1')
            return
    if len(pas)==3 and pas[1]!=pas[2]:
        self.response.out.write('2')
        return
    self.response.out.write('1')
    return

def addProject(self,pcode):
    username=self.request.get('UserName')
    if pcode=='1':#添加a1的基本资讯订阅
        sub=Subscribe().all().filter('userName =',username).filter('maincode =','a1').fetch(1)
        if len(sub)==0:
            s=Subscribe()#资讯
            s.userName=username
            s.maincode='a1'
            s.subscribeType='1'
            s.status='1'
            s.put()
        else:
            s=sub[0]
            s.status='1'
            s.lastUpdateTime=datetime.datetime.now()
            s.put()
        s = SubscribeOther()#订阅RSS资讯设置
        s.userName = username
        s.maincode = 'a1'
        s.code = 'a1-9'
        s.father = 'a1'
        s.level = '2'
        s.subscribeType = '1'
        s.put()
        ####
        replyContent = ReplyContent()
        replyContent.maincode = 'a1'#主编号
        replyContent.code = 'a1-9-1-s'+username#编号
        replyContent.father = 'a1-9-1'#父级
        replyContent.content = '**订阅的资讯****'.decode('utf-8')#内容
        replyContent.replyType = '7'
        replyContent.status = '1'
        replyContent.level='100'
        rlist=ReplyContent().all().filter('code =',replyContent.code)
        if rlist.count()!=0:
            db.delete(rlist.fetch(10))
        replyContent.put()
        replyContent = ReplyContent()
        replyContent.maincode = 'a1'#主编号
        replyContent.code = 'a1-9-4-s'+username#编号
        replyContent.father = 'a1-9-4'#父级
        replyContent.content = '**资讯：#20#****'.decode('utf-8')#内容
        replyContent.replyType = '8'
        replyContent.status = '1'
        replyContent.level='100'
        rlist=ReplyContent().all().filter('code =',replyContent.code)
        if rlist.count()!=0:
            db.delete(rlist.fetch(10))
        replyContent.put()
        re=ReplyContent()
        re.maincode = 'a1'#主编号
        re.code = 'a1-9-4-s'+username+'-1'#编号
        re.father = 'a1-9-4-s'+username#父级
        re.content ='******'#内容
        re.replyType = '1'
        re.status = '1'
        re.level='101'
        rlist=ReplyContent().all().filter('code =',re.code)
        if 0==rlist.count():
            re.put()
        ####
        s = SubscribeOther()#热门RSS资讯
        s.userName = username
        s.maincode = 'a1'
        s.code = 'a1-9-1'
        s.father = 'a1-9'
        s.level = '3'
        s.subscribeType = '1'
        s.put()
        s = SubscribeOther()#热门RSS资讯
        s.userName = username
        s.maincode = 'a1'
        s.code = 'a1-9-1-s'+username
        s.father = 'a1-9-1'
        s.level = '100'
        s.subscribeType = '0'
        s.put()
        s = SubscribeOther()#分类RSS资讯
        s.userName = username
        s.maincode = 'a1'
        s.code = 'a1-9-2'
        s.father = 'a1-9'
        s.level = '3'
        s.subscribeType = '0'
        s.put()
        s = SubscribeOther()#搜索RSS资讯
        s.userName = username
        s.maincode = 'a1'
        s.code = 'a1-9-3'
        s.father = 'a1-9'
        s.level = '3'
        s.subscribeType = '0'
        s.put()
        s = SubscribeOther()#取消RSS资讯订阅
        s.userName = username
        s.maincode = 'a1'
        s.code = 'a1-9-4'
        s.father = 'a1-9'
        s.level = '3'
        s.subscribeType = '1'
        s.put()
        s = SubscribeOther()#用户搜索的资讯
        s.userName = username
        s.maincode = 'a1'
        s.code = 'a1-9-4-s'+username
        s.father = 'a1-9-4'
        s.level = '100'
        s.subscribeType = '0'
        s.put()
        rlist=ReplyContent().all().filter('code =','a999-1-s1-'+username).fetch(1)
        if rlist:
            rc=rlist[0]
            rc.content='**1**'
            rc.put()
#        s = SubscribeOther()#取消用户搜索的资讯
#        s.userName = username
#        s.maincode = 'a1'
#        s.code = 'a1-9-9-s'+username
#        s.father = 'a1-9-9'
#        s.level = '100'
#        s.subscribeType = '0'
#        s.put()
def delProject(self,pcode):
    username=self.request.get('UserName')
    if pcode=='1':#删除a1的所有订阅
        subscribe=db.GqlQuery("SELECT * FROM Subscribe WHERE userName=:1 AND maincode=:2",username,'a1').fetch(1)
        subscribeList=findSubscribeOthers([],username,'a1')
        db.delete(subscribeList)
        for s in subscribe:
            s.status='0'
            s.lastUpdateTime=datetime.datetime.now()
            s.put()
        rlist=ReplyContent().all().filter('code =','a999-1-s1-'+username).fetch(1)
        if rlist:
            rc=rlist[0]
            rc.content='****'
            rc.put()
        dellist=ReplyContent().all().filter('code =','a1-9-1-s'+username).fetch(1)
        dellist+=ReplyContent().all().filter('code =','a1-9-4-s'+username).fetch(1)
        con=[]
        for replyc in dellist:
            con+=getAllReplyInfoByFather(replyc.code)
        db.delete(dellist)
        db.delete(con)
def doDingYue(self):
    rdy=[]
    ndy=[]
    ddy=self.request.get('Content').split('$')
    if len(ddy)==2:
        rdy=ddy[0].split('*')
        ndy=ddy[1].split('*')
        for r in rdy:
            if r not in ndy:
            #删除对应项目
                delProject(self,r)
                pass
        for n in ndy:
            if n not in rdy:
            #添加对应项目
                addProject(self,n)
                pass
        self.response.out.write('0')
        return
#对a1的处理
def ToA1(self):#RssChangeScribe 的处理逻辑
    userName = self.request.get('UserName')
    for s in self.request.query_string.split('&'):
        if 'Content'==s[0:7] and len(s)>8:
            unquotedPath= urllib.unquote(s[8:])
#            unquotedPath = unquote(path)
            try:
                content = unicode(unquotedPath, 'utf8')
            except:
                try:
                  content = unicode(unquotedPath, 'gbk')
                except:
                    content=''
#    content=self.request.get('Content')
    codestr=content.split('$')
    if 'a1-9-1-s'+userName ==self.request.get('Code'):
        delcode=codestr[1].split('*')
        dels=[]
        for d in delcode:
            dels+=SubscribeOther().all().filter('code =',d).filter('userName =',userName).fetch(1)
        db.delete(dels)
        ##a1-9-1-sN节点内容修改
        updateA1N(userName)
        updateA1(userName)
        pass
    elif 'a1-9-2-s1' ==self.request.get('Code') or 'a1-9-3-s1' ==self.request.get('Code'):
        addcode=codestr[1].split('*')
        for c in addcode:
            AddSub(userName,c,'0')
        ##a1-9-1-sN节点内容修改
        updateA1N(userName)
        updateA1(userName)
        pass
    elif 'a1-9-4-s'+userName ==self.request.get('Code'):
        if content.find('**')>-1:
            keyword=content.replace('*','')
            content2list=ContentClass().all().filter('maincode =','a1').filter('level =','2')
            content3list=ContentClass().all().filter('maincode =','a1').filter('level =','3').order('code')
            contentmap={}
            keymap={}
            confirst=[]
            for con in content2list:
                if con.code<'a1-9':
                    contentmap[con.code]=con
            for con in content3list:
                if con.code[-1:]=='R':
                    continue
                contentmap[con.code]=con
                if contentmap.has_key(con.father):
                    fcon=contentmap[con.father]
                else:
                    fcon=None
                if fcon:
                    keymap[con.content+fcon.content]=con
                else:
                    keymap[con.content]=con
            for c in keymap.keys():
                if keyword in c:
                    confirst.append(keymap[c].code)
            confirst.sort()
            writemap={}
            for c in confirst:
                c2=contentmap[c]
                if not writemap.has_key(c2.father):
                    writemap[c2.father]=[]
                writemap[c2.father].append(c2)
            writset=list(writemap.keys())
            writset.sort()
            writestr='**资讯：#20#**'.decode('utf-8')
            flag=False
            for l in writset:
                if contentmap.has_key(l):
                    writestr+=contentmap[l].content
                    for contemp in writemap[l]:
                        writestr+='*'+contemp.content+'*'+contemp.code
                    writestr+='**'
                    flag=True
            if not flag:
                writestr+='**'
            replayCont=ReplyContent().all().filter('code =','a1-9-4-s'+userName).fetch(1)
            if replayCont:
                replayCont=replayCont[0]
                replayCont.content=writestr.replace('\r','').replace('\n','')
                replayCont.lastUpdateTime=datetime.datetime.now()
                replayCont.put()
                keycontent=ReplyContent().all().filter('code =','a1-9-4-s'+userName+'-1').fetch(1)
                if keycontent:
                    re=keycontent[0]
                    re.content='**'+keyword+'**'
                    re.lastUpdateTime=datetime.datetime.now()
                    re.put()
                else:
                    re=ReplyContent()
                    re.maincode = 'a1'#主编号
                    re.code = 'a1-9-4-s'+userName+'-1'#编号
                    re.father = 'a1-9-4-s'+userName#父级
                    re.content ='**'+keyword+'**'#内容
                    re.replyType = '1'
                    re.status = '1'
                    re.level='101'
                    re.put()
            pass#模糊搜素
        else:
            addcode=codestr[1].split('*')
            for c in addcode:
                AddSub(userName,c,'0')
            ##a1-9-1-sN节点内容修改
            updateA1N(userName)
            updateA1(userName)
            pass

    self.response.out.write('0')

###更新a1-9-1-sN的内容
def updateA1N(userName):
    replycontent=ReplyContent().all().filter('code =','a1-9-1-s'+userName).fetch(1)
    if replycontent:
        replycontent=replycontent[0]
        contentlist=ContentClass().all().filter('maincode =','a1').filter('level in',['2','3'])
        contentmap={}
        for con in contentlist:
            contentmap[con.code]=con
        contentset=contentmap.keys()
        sub=SubscribeOther().all().filter('code >','a1-').filter('code <','a1-9').filter('level =','2').filter('userName =',userName).order('code')
        sub3=SubscribeOther().all().filter('code >','a1-').filter('code <','a1-9').filter('level =','3').filter('userName =',userName).order('code')
        confirst=[]
        consecond={}
        for s in sub:
            confirst.append(s.code)
            consecond[s.code]=[]
        conset=consecond.keys()
        for s in sub3:
            if s.father in conset and s.code in contentset:
                consecond[s.father].append(contentmap[s.code])
            else:
                logging.error('error sub '+s.code)
        confirst.sort()
        strcontent='**订阅的资讯**'.decode('utf-8')
        flag=False
        for c in confirst:
            if c in contentset:
                strcontent+=contentmap[c].content
                for content in consecond[c]:
                    strcontent+='*'+content.content+'*'+content.code
                strcontent+='**'
                flag=True
        if not flag:
            strcontent+='**'
        replycontent.content=strcontent.replace('\r','').replace('\n','')
        replycontent.put()

    pass
##更新a1的时间
def updateA1(userName):
    a1sub=Subscribe().all().filter('code =','a1').filter('userName =',userName).fetch(1)
    if a1sub:
        s=a1sub[0]
        s.lastUpdateTime=datetime.datetime.now()
        s.put()
##订阅内容，验证父级是否订阅
def AddSub(username,code,type='1'):
    if not code:
        return
    if SubscribeOther().all().filter('code =',code).filter('userName =',username).count()==1:
        return
    codesplit=code.split('-')
    if len(codesplit)==1:
        fsub=Subscribe().all().filter('maincode =',code).filter('userName =',username).fetch(1)
        if not fsub:
            s=Subscribe()#资讯
            s.userName=username
            s.maincode=code
            s.subscribeType='1'
            s.status='1'
            s.put()
        return
    fathercode=''
    for c in codesplit[:-1]:
        fathercode+=c+'-'
    if fathercode:
        fathercode=fathercode[:-1]
    if fathercode.find('-')>-1:
        fsub=SubscribeOther().all().filter('code =',fathercode).filter('userName =',username).fetch(1)
    else:
        fsub=Subscribe().all().filter('maincode =',fathercode).filter('userName =',username).fetch(1)
        if not fsub:
            s=Subscribe()#资讯
            s.userName=username
            s.maincode=code
            s.subscribeType='1'
            s.status='1'
            s.put()
            fsub.append(s)
    if not fsub:
        AddSub(username,fathercode)
    if code.find('s')>-1:
        level=str(99+len(code[code.find('s'):].split('-')))
    else:
        level=str(len(codesplit))
    s = SubscribeOther()#取消RSS资讯订阅
    s.userName = username
    s.maincode = 'a1'
    s.code =code
    s.father = fathercode
    s.level = level
    s.subscribeType = type
    s.put()
#用户回复接口
class AddReply(webapp.RequestHandler):
    def get(self):
        try:
            m=self.request.get('MainCode')
            c=self.request.get('Code').split('-')
            if len(c)==0 or c[0]!=m:
                self.response.out.write('1')
                return
            if not checkUser(self):
                self.response.out.write('1')
                return
            try:
                if 'a999-9-1-s1' == self.request.get('Code'):
                    return doRePassWord(self)
                if 'a999-1-s1' ==self.request.get('Code'):
                    return doDingYue(self)
                if 'a999-2-s1' == self.request.get('Code'):
                    return doShouQuan(self)
                if 'a1'==self.request.get('MainCode'):
                    return ToA1(self)
                if 'a3'==self.request.get('MainCode') or 'a33'==self.request.get('MainCode'):
                    return A3replay(self)#对微博的回复处理，
#                    self.redirect('/RssChangeScribe'+parm,permanent=True)
            except Exception,e:
                logging.error('0000'+str(e))
                self.response.out.write('1')
                return
                    
            greeting = Reply()
            greeting.maincode=self.request.get('MainCode')
            greeting.userName = self.request.get('UserName')
            greeting.code= self.request.get('Code')
            greeting.replyContent= self.request.get('Content')
            greeting.replyType= self.request.get('Type')
            greeting.replyTime=getCurrentTime()
            if greeting.maincode and greeting.userName and greeting.code and greeting.replyType :
                greeting.put()
                self.response.out.write('0')
            else:
                raise
        except:
            self.response.out.write('1')

#用户定制的所有图库 5-20  http://localhost:8084/PhotoAll?UserName=f123456&LibType=All
class PhotoLibAll(webapp.RequestHandler):
    def get(self):
        try:
            if not checkUser(self):
                self.response.out.write('1')
                return 
            userName = self.request.get('UserName')
            user_photoLibs=db.GqlQuery("SELECT * FROM User_PhotoLib WHERE userName=:1 ORDER BY photoLibType ASC",userName)
            self.response.out.write('%s'%time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
            self.response.out.write('\r\n')
            for user_photoLib in user_photoLibs:
                if user_photoLibs:
                    self.response.out.write('$$')
                    if user_photoLib.photoLibType=='1':
                        self.response.out.write('Sys')
                    if user_photoLib.photoLibType=='2':
                        self.response.out.write('User')
                    if user_photoLib.photoLibType=='3':
                        self.response.out.write('Tmp')
                    self.response.out.write('$$')
                    self.response.out.write('\r\n')
                    greetings=db.GqlQuery("SELECT * FROM PhotoLib_Photo WHERE photoLibCode=:1 AND status='1' ORDER BY lastUpdateTime  ASC",user_photoLib.photoLibCode)
                    for greeting in greetings:
                        photos=db.GqlQuery("SELECT * FROM Images WHERE photoCode=:1",greeting.photoCode)
                        for photo in photos:
                            self.response.out.write('$$')
                            if photo.photoCode:
                                self.response.out.write('%s' % photo.photoCode.encode('utf-8'))
                                self.response.out.write('$$')
                                self.response.out.write("%s" %photo.name.encode('utf-8') )
                                self.response.out.write('$$')
                            self.response.out.write('\r\n')
        except Exception,e:
            self.response.out.write('1')
            self.response.out.write(str(e))

#图库更新接口 
#http://localhost:8084/PhotoUpdate?UserName=f123456&LibType=All&LastUpdateTime=2010-01-0112:23:30*2010-01-0112:23:30*2010-01-0112:23:30
#http://localhost:8084/PhotoUpdate?UserName=f123456&LibType=All&LastUpdateTime=2010-09-0112:23:30*2010-01-0112:23:30*2010-01-0112:23:30
#http://localhost:8084/PhotoUpdate?UserName=f123456&LibType=All&LastUpdateTime=2010-09-0112:23:30*2010-09-0112:23:30*2010-09-0112:23:30
#http://localhost:8084/PhotoUpdate?UserName=f123456&LibType=Sys&LastUpdateTime=2010-01-0112:23:30*2010-01-0112:23:30*2010-01-0112:23:30
#http://localhost:8084/PhotoUpdate?UserName=f123456&LibType=Sys&LastUpdateTime=2010-09-0112:23:30*2010-09-0112:23:30*2010-09-0112:23:30
class PhotoUpdate(webapp.RequestHandler):
    def get(self):
        try:
            if not checkUser(self):
                self.response.out.write('1')
                return 
            UserName = self.request.get('UserName')
            LastUpdateTime=self.request.get('LastUpdateTime')
            if not UserName or not LastUpdateTime:
                raise
            user_photoLibs=db.GqlQuery("SELECT * FROM User_PhotoLib WHERE userName=:1 ORDER BY photoLibType ASC",UserName)
            CurrentTime=datetime.datetime.now() #//获取当前时间
            self.response.out.write('%s'%time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
            self.response.out.write('\r\n')
            LastUpdateTime = datetime.datetime.strptime(LastUpdateTime,'%Y-%m-%d %H:%M:%S')#系统图库最后更新时间
            for lib in user_photoLibs:
                photoLib=db.GqlQuery("SELECT * FROM PhotoLib WHERE photoLibCode=:1 ",int(lib.photoLibCode)).fetch(1)
                
                if (CurrentTime-LastUpdateTime).days>10 or lib.lastUpdateTime>LastUpdateTime or photoLib[0].date>LastUpdateTime:
                    self.response.out.write('GET')
                    self.response.out.write('\r\n')
                    getPhotoUpdate_GET(self,lib.photoLibType,UserName) 
                else:
                    self.response.out.write('Update')
                    self.response.out.write('\r\n')
                    getPhotoUpdate_Update(self,lib.photoLibType,UserName,LastUpdateTime) 
            return
        except Exception,e:
            self.response.out.write('1')
            self.response.out.write(str(e))

def getPhotoUpdate_GET(self,photoLibType,userName):
    try:
        user_photoLibs=db.GqlQuery("SELECT * FROM User_PhotoLib WHERE userName=:1 AND photoLibType=:2",userName,photoLibType)
        for user_photoLib in user_photoLibs:
            if user_photoLibs:
                self.response.out.write('$$')
                if user_photoLib.photoLibType=='1':
                    self.response.out.write('Sys')
                if user_photoLib.photoLibType=='2':
                    self.response.out.write('User')
                if user_photoLib.photoLibType=='3':
                    self.response.out.write('Tmp')
                self.response.out.write('$$')
                self.response.out.write('\r\n')
                greetings=db.GqlQuery("SELECT * FROM PhotoLib_Photo WHERE photoLibCode=:1 AND status='1' ORDER BY lastUpdateTime ASC",user_photoLib.photoLibCode)
                for greeting in greetings:
#                    if greeting.status!=0:
                    photos=db.GqlQuery("SELECT * FROM Images WHERE photoCode=:1",greeting.photoCode)
                    for photo in photos:
                        self.response.out.write('$$')
                        self.response.out.write('%s' % photo.photoCode.encode('utf-8'))
                        self.response.out.write('$$')
                        self.response.out.write("%s" %photo.name.encode('utf-8') )
                        self.response.out.write('$$')
#                            self.response.out.write("image/%s" %id )
#                            self.response.out.write('$$')
                            #self.response.out.write('%s' % photo.name.encode('utf-8'))
                            #self.response.out.write('$$')
                            #id = string.atoi(photo.photoCode)
                            #self.response.out.write('<a href="/s/%s"' %id)
                            #self.response.out.write('target="_black"><img  src="/s/%s"' %id)
                            #self.response.out.write('alt="%s"' %photo.name.encode('utf-8'))
                            #self.response.out.write('/></a>')
                            #self.response.out.write('$$')
                        self.response.out.write('\r\n')
    except Exception,e:
        self.response.out.write('1')
        self.response.out.write(str(e))

def getPhotoUpdate_Update(self,photoLibType,userName,LastUpdateTime):
    try:
        user_photoLibs=db.GqlQuery("SELECT * FROM User_PhotoLib WHERE userName=:1 AND photoLibType=:2",userName,photoLibType)
        for user_photoLib in user_photoLibs:
            if user_photoLibs:
                self.response.out.write('$$')
                if user_photoLib.photoLibType=='1':
                    self.response.out.write('Sys')
                if user_photoLib.photoLibType=='2':
                    self.response.out.write('User')
                if user_photoLib.photoLibType=='3':
                    self.response.out.write('Tmp')
                self.response.out.write('$$')
                self.response.out.write('\r\n')
                greetings=db.GqlQuery("SELECT * FROM PhotoLib_Photo WHERE  photoLibCode=:1 AND lastUpdateTime>:2 ORDER BY lastUpdateTime ASC",user_photoLib.photoLibCode,LastUpdateTime)
                for greeting in greetings:
                    photos=db.GqlQuery("SELECT * FROM Images WHERE photoCode=:1",greeting.photoCode)
                    for photo in photos:
                        self.response.out.write('$$')
                        self.response.out.write('%s' % photo.photoCode.encode('utf-8'))
                        self.response.out.write('$$')
                        self.response.out.write("%s" %photo.name.encode('utf-8') )
                        self.response.out.write('$$')
                        self.response.out.write(greeting.status.encode('utf-8'))
                        self.response.out.write('$$')
                        self.response.out.write('\r\n')
    except Exception,e:
        self.response.out.write('1')
        self.response.out.write(str(e))
        

from xml.dom.minidom import Document
##所有资讯
#http://localhost:8084/InfoAll?UserName=f123456&MainCode=a6
class InfoAll(webapp.RequestHandler):
    def get(self):
        try:
            if not checkUser(self):
                self.response.out.write('1')
                return 
            UserName = self.request.get('UserName')
            xml = self.request.get('xml',None)
            if not UserName:
                raise
            #加入更新微博的方法
            updateWeibo(UserName)
            MainCode = self.request.get('MainCode')
            getAllInfoByUserNameAndMainCode(self,UserName,MainCode,None,xml)
        except Exception,e:
            logging.error('infoall:'+str(e))
            self.response.out.write("1")
def infoallxml(content,xml=None,datas=None,delete=None):
    if not xml:
        xml=Document()
        datas=xml.createElement('datas')
        datas.setAttribute('time','%s' %time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
#        datas.setAttribute('type','infoall')
        xml.appendChild(datas)
    for c in content:
        data=xml.createElement('data')
        if c.status=='1' and not delete:
            data.setAttribute('code',c.code or '')
            data.setAttribute('father',c.father or '')
            if hasattr(c,'title'):
                if c.title:
                    data.setAttribute('title',c.title or '')
                if c.updateSpanTime:
                    data.setAttribute('updateSpanTime',c.updateSpanTime or '')

            else:
                if c.replyType:
                    data.setAttribute('replyType',c.replyType or '')
                
            data.setAttribute('maincode',c.maincode or '')
            data.setAttribute('level',c.level or '')
            if c.content:
                data.appendChild(xml.createTextNode(c.content or ''))
            data.setAttribute('status',c.status or '')
            data.setAttribute('lastUpdateTime',str(c.lastUpdateTime) or '')
        else:
            if not hasattr(c,'code'):
                data.setAttribute('code',c.maincode or '')
            else:
                data.setAttribute('code',c.code or '')
            data.setAttribute('status','0' or '')
        datas.appendChild(data)
    return (xml,datas)



def getAllInfoByUserNameAndMainCode(web,UserName,MainCode,lastTime,xml=None):#获取所有的订阅资讯
    if not lastTime:
        #web.response.out.write('%s' %time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
        #web.response.out.write('\r\n')
        pass
    if not MainCode or getCodeLength(MainCode)<=1:#用户订阅的某个第一层资讯
        contents=[]#资讯列表
        if MainCode=='' or MainCode==None:
            subscribeOthers = db.GqlQuery("SELECT * FROM SubscribeOther WHERE userName=:1 ",UserName).fetch(100)
            subscribes = db.GqlQuery("SELECT * FROM Subscribe WHERE userName=:1  AND status='1' ORDER BY maincode ASC",UserName).fetch(100)
            subscribeOthers += db.GqlQuery("SELECT * FROM SubscribeOther WHERE userName=:1 ",'000').fetch(30)
#            subscribeOthers += db.GqlQuery("SELECT * FROM SubscribeOther WHERE father=:1 AND code=:2 ",'a999-1-s1','a999-1-s1'+'-'+UserName).fetch(1000)
            subscribes += db.GqlQuery("SELECT * FROM Subscribe WHERE userName=:1  AND status='1' ORDER BY maincode ASC",'000').fetch(10)
        else:
            subscribeOthers = db.GqlQuery("SELECT * FROM SubscribeOther WHERE userName=:1 AND maincode=:2 ",UserName,MainCode)
            subscribes = db.GqlQuery("SELECT * FROM Subscribe WHERE userName=:1 AND maincode=:2 AND status='1'  ORDER BY maincode ASC",UserName,MainCode)
        for subscribeOther  in subscribeOthers :
            contents=getContentAndReply(contents,subscribeOther.subscribeType,subscribeOther.code)
        for sub in subscribes:
            contents=getContentAndReply(contents,sub.subscribeType,sub.maincode)

        #########输出xml
        if xml:
            web.response.out.write(infoallxml(contents)[0].toxml('utf-8'))
        else:
            getUserAllInfo(web,contents)
        #############输出数据
        #getUserAllInfo(web,contents)
def getContentAndReply(contents,type,code):
    subContent= db.GqlQuery("SELECT * FROM ContentClass WHERE code = :1 AND status='1' ORDER BY code ASC", code).fetch(1)
    subContent+= db.GqlQuery("SELECT * FROM ReplyContent WHERE code = :1 AND status='1' ORDER BY code ASC", code).fetch(1)
    contents += subContent
    if type=='0':#资讯全要
        con=db.GqlQuery("SELECT * FROM ContentClass WHERE code > :1 AND  code < :2 AND status='1' ORDER BY code ASC", code+'-',code+'-'+u"\ufffd").fetch(200)
        con+=db.GqlQuery("SELECT * FROM ReplyContent WHERE code > :1 AND  code < :2 AND status='1' ORDER BY code ASC", code+'-',code+'-'+u"\ufffd").fetch(200)
#        con=getAllInfoByFather(code)+subContent
#        for c in con:
#            con+=getAllReplyInfoByFather(c.code)
        contents+=con
    return contents
def getAllInfoByFather(code):
    contents = db.GqlQuery("SELECT * FROM ContentClass WHERE father = :1 AND status='1'", code).fetch(100)
    con=[]
    for c in contents:
        con+=getAllInfoByFather(c.code)
    return contents+con
def getAllReplyInfoByFather(code):
    contents = db.GqlQuery("SELECT * FROM ReplyContent WHERE father = :1 AND status='1'", code).fetch(100)
    con=[]
    for c in contents:
        con+=getAllReplyInfoByFather(c.code)
    return contents+con
def getUpdateContentAndReply(contents,type,code,lastUpdateTime=None):
    subContent= db.GqlQuery("SELECT * FROM ContentClass WHERE code = :1 ", code).fetch(1)
    subContent+= db.GqlQuery("SELECT * FROM ReplyContent WHERE code = :1 ", code).fetch(1)
    if not subContent:
        return contents
    contents += subContent
    if type=='0' and subContent[0].status=='1':#资讯全要
        if lastUpdateTime:
            con=[]
            for c in ContentClass().all().filter('code >',code+'-').filter('code <',code+'-'+u"\ufffd"):
                if c.lastUpdateTime>lastUpdateTime:
                    con.append(c)
            for c in ReplyContent().all().filter('lastUpdateTime >',lastUpdateTime):
                if c.code>code+'-' and c.code<code+'-'+u"\ufffd":
                    con.append(c)

        else:
            con=[]
            for c in ContentClass().all().filter('code >',code+'-').filter('code <',code+'-'+u"\ufffd").filter('status =','1'):
                con.append(c)
            for c in ReplyContent().all().filter('code >',code+'-').filter('code <',code+'-'+u"\ufffd").filter('status =','1'):
                con.append(c)
#        con=getUpdateAllInfoByFather(code)+subContent
#        for c in con:
#            if c.status=='1':
#                con+=getUpdateAllReplyInfoByFather(c.code)
        contents+=con
    return contents
def getUpdateAllInfoByFather(code):
    contents = db.GqlQuery("SELECT * FROM ContentClass WHERE  father = :1 ", code).fetch(100)
    con=[]
    for c in contents:
        if c.status=='1':
            con+=getUpdateAllInfoByFather(c.code)
    return contents+con
def getUpdateAllReplyInfoByFather(code):
    contents = db.GqlQuery("SELECT * FROM ReplyContent WHERE   father = :1 ", code).fetch(100)
    con=[]
    for c in contents:
        if c.status=='1':
            con+=getUpdateAllReplyInfoByFather(c.code)
    return contents+con

def getNew(contents,updatetime):
    newcontent=[]
    for c in contents:
        if c.lastUpdateTime>updatetime:
            newcontent.append(c)
    return newcontent

#2011-10-7日换为xml版
class InfoUpdateXML(webapp.RequestHandler):
    def get(self):
        try:
            if not checkUser(self):
                self.response.out.write('1')
                return
            UserName = self.request.get('UserName')
            AllLastUpdateTime=self.request.get('AllLastUpdateTime')
            if not UserName or not AllLastUpdateTime:
                raise
            #加入更新微博的方法
            updateWeibo(UserName)
            AllLastUpdateTime=datetime.datetime.strptime(AllLastUpdateTime,'%Y-%m-%d %H:%M:%S')
            CurrentTime=datetime.datetime.now()
            if(CurrentTime-AllLastUpdateTime).days>10:
                #self.response.out.write('Get\r\n')
                getAllInfoByUserNameAndMainCode(self,UserName,None,None)
            else:
                subscribes = db.GqlQuery("SELECT * FROM Subscribe WHERE lastUpdateTime>:1 AND userName=:2 ORDER BY lastUpdateTime ASC",AllLastUpdateTime,UserName).fetch(100)
                oldSubscribes = db.GqlQuery("SELECT * FROM Subscribe WHERE lastUpdateTime<:1 AND userName=:2 ORDER BY lastUpdateTime ASC",AllLastUpdateTime,UserName).fetch(100)
                subscribes += db.GqlQuery("SELECT * FROM Subscribe WHERE lastUpdateTime>:1 AND userName=:2 ORDER BY lastUpdateTime ASC",AllLastUpdateTime,'000').fetch(30)
                oldSubscribes += db.GqlQuery("SELECT * FROM Subscribe WHERE lastUpdateTime<:1 AND userName=:2 ORDER BY lastUpdateTime ASC",AllLastUpdateTime,'000').fetch(30)
                #########
                xml=None
                datas=None
                updateContent=[]
                for sub in subscribes:
                    if sub.status=='0':
                        xml,datas=infoallxml([sub],xml,datas,'del')
                        pass#删除订阅
                    else:
                        if sub.subscribeType=='1':#下面的另外订阅
                            c=db.GqlQuery("SELECT * FROM ContentClass WHERE code = :1",sub.maincode).fetch(1)
                            if len(c)==1 and c[0].status=='1':
                                subscribeOthers = db.GqlQuery("SELECT * FROM SubscribeOther WHERE userName=:1 AND maincode=:2 ",UserName,sub.maincode)
                                for subscribeOther  in subscribeOthers :
                                    xml,datas=infoallxml(getUpdateContentAndReply([],subscribeOther.subscribeType,subscribeOther.code),xml,datas)
                        else:
                            xml,datas=infoallxml(getUpdateContentAndReply([],sub.subscribeType,sub.maincode),xml,datas)
                for sub in oldSubscribes:
                    if sub.status=='0':
                        xml,datas=infoallxml([sub],xml,datas,'del')
                        pass #删除订阅
                    else:
                        if sub.subscribeType=='1':#下面的另外订阅
                            c=db.GqlQuery("SELECT * FROM ContentClass WHERE code = :1",sub.maincode).fetch(1)
                            if len(c)==1 and c[0].status=='1':
                                subscribeOthers = db.GqlQuery("SELECT * FROM SubscribeOther WHERE userName=:1 AND maincode=:2 ",UserName,sub.maincode)
                                for subscribeOther  in subscribeOthers :
                                    xml,datas=infoallxml(getUpdateContentAndReply([],subscribeOther.subscribeType,subscribeOther.code,AllLastUpdateTime),xml,datas)
                        else:
                            xml,datas=infoallxml(getUpdateContentAndReply([],sub.subscribeType,sub.maincode,AllLastUpdateTime),xml,datas)
                if xml:
                    self.response.out.write(xml.toxml('utf-8'))
        except Exception,e:
            logging.error('0000'+str(e))
            self.response.out.write('1\r\n')

#2011-2-23日重构
class InfoUpdate(webapp.RequestHandler):
    def get(self):
        try:
            if not checkUser(self):
                self.response.out.write('1')
                return 
            UserName = self.request.get('UserName')
            AllLastUpdateTime=self.request.get('AllLastUpdateTime')
            if not UserName or not AllLastUpdateTime:
                raise
            #加入更新微博的方法
            updateWeibo(UserName)
            AllLastUpdateTime=datetime.datetime.strptime(AllLastUpdateTime,'%Y-%m-%d %H:%M:%S')
            CurrentTime=datetime.datetime.now()
            if(CurrentTime-AllLastUpdateTime).days>10:
                self.response.out.write('Get\r\n')
                getAllInfoByUserNameAndMainCode(self,UserName,None,None,'xml')
            else:
                subscribes = db.GqlQuery("SELECT * FROM Subscribe WHERE lastUpdateTime>:1 AND userName=:2 ORDER BY lastUpdateTime ASC",AllLastUpdateTime,UserName).fetch(100)
                oldSubscribes = db.GqlQuery("SELECT * FROM Subscribe WHERE lastUpdateTime<:1 AND userName=:2 ORDER BY lastUpdateTime ASC",AllLastUpdateTime,UserName).fetch(100)
                subscribes += db.GqlQuery("SELECT * FROM Subscribe WHERE lastUpdateTime>:1 AND userName=:2 ORDER BY lastUpdateTime ASC",AllLastUpdateTime,'000').fetch(100)
                oldSubscribes += db.GqlQuery("SELECT * FROM Subscribe WHERE lastUpdateTime<:1 AND userName=:2 ORDER BY lastUpdateTime ASC",AllLastUpdateTime,'000').fetch(100)
                #########
                updateCode=[]
                updateContent=[]
                updateAllContent=[]
                for sub in subscribes:
                    if sub.status=='0':
                        updateCode.append(sub.maincode)
                    else:
                        updateAllContent+=db.GqlQuery("SELECT * FROM ContentClass WHERE  status='1' AND code = :1 ",sub.maincode).fetch(1)
                for dc in updateCode:
                    for c in db.GqlQuery("SELECT * FROM ContentClass WHERE code = :1 ORDER BY code ASC", dc).fetch(1):
                        c.status='0'
                        updateContent.append(c)
                ###########
                tempUpdateContent=[]
                for sub in oldSubscribes:
                    if sub.status=='0':
                        continue
                    else:
                        if sub.subscribeType=='1':
                            c=db.GqlQuery("SELECT * FROM ContentClass WHERE code = :1",sub.maincode).fetch(1)
                            tempUpdateContent+=c
                            if len(c)==1 and c[0].status=='1':
                                subscribeOthers = db.GqlQuery("SELECT * FROM SubscribeOther WHERE userName=:1 AND maincode=:2 ",UserName,sub.maincode)
                                for subscribeOther  in subscribeOthers :
                                    tempUpdateContent=getUpdateContentAndReply(tempUpdateContent,subscribeOther.subscribeType,subscribeOther.code)
                        else:
                            tempUpdateContent=getUpdateContentAndReply(tempUpdateContent,sub.subscribeType,sub.maincode)
                for tc in tempUpdateContent:
                    if tc.lastUpdateTime>AllLastUpdateTime:
                        updateContent.append(tc)
                ###########
                self.response.out.write('Update\r\n')
                self.response.out.write('%s' %time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
                self.response.out.write('\r\n')
                if updateContent:
                    getUserAllInfo(self,updateContent,True)
                if updateAllContent:
                    codeMap=[]
                    contentMapFather={}
                    for contentItem in updateAllContent:
                        codeMap.append(contentItem.code)
                        contentMapFather[contentItem.code]=contentItem
                    ###排序结束
                    codeMap.sort()
                    for code in codeMap:#按序遍历
                        c=contentMapFather[code]
                        self.response.out.write('Get:'+c.code.encode('utf-8')+'\r\n')
                        getAllInfoByUserNameAndMainCode(self,UserName,c.code,True)
        except Exception,e:
            logging.error('0000'+str(e))
            self.response.out.write('1\r\n')
###获取用户订阅的全部内容###
def getUserAllInfo(self,contents,isUpdate=False):
    title_flag = False#是否已经输出标题
    contentMap={}
    for content in contents:
        k=(int(content.level),content.father)
        if contentMap.has_key(k):
            contentMap[k].append(content)
        else:
            contentMap[k]=[]
            contentMap[k].append(content)
    keylist=list(contentMap.keys())
    keylist.sort(key=lambda x:(x[0],x[1]))
    items=set()
    for item,f in keylist:
        codeMap=[]
        contentMapFather={}
        for contentItem in contentMap[(item,f)]:
            codeMap.append(contentItem.code)
            contentMapFather[contentItem.code]=contentItem
        ###排序结束
        codeMap.sort()
        for code in codeMap:#按序遍历
            content=contentMapFather[code]
            if content.code in items:
                continue
            items.add(content.code)
            if item==1:
                if title_flag == False:
                    self.response.out.write('$$'+content.level.encode('utf-8')+'$$')
                    self.response.out.write('蘑菇网$$\r\n')
                title_flag = True
                self.response.out.write('$$'+content.code.encode('utf-8'))
                self.response.out.write('$$'+replaceChar(content.content).encode('utf-8'))
                self.response.out.write('$$'+content.updateSpanTime.encode('utf-8'))
                if isUpdate:
                    self.response.out.write('$$'+content.status.encode('utf-8'))
            else:
                if title_flag == False:
                    self.response.out.write('$$'+content.level.encode('utf-8')+'$$')
                    self.response.out.write(content.maincode.encode('utf-8')+'$$')
                    self.response.out.write(content.father.encode('utf-8')+'$$')
                    if item<100:
                        l=db.GqlQuery("SELECT * FROM ContentClass WHERE code=:1",content.father).fetch(1)
                        if len(l)==1:
                            self.response.out.write(replaceChar(l[0].title).encode('utf-8')+'$$')
                    self.response.out.write('\r\n')
                    title_flag = True
                self.response.out.write('$$'+content.code.encode('utf-8'))
                if item<100:
                    self.response.out.write('$$'+replaceChar(content.content).encode('utf-8'))
                else:
                    self.response.out.write('$$'+replaceChar(content.content).encode('utf-8'))
                    self.response.out.write('$$'+content.replyType.encode('utf-8'))#特殊节点的回复类型
                if isUpdate:
                    self.response.out.write('$$'+content.status.encode('utf-8'))
        self.response.out.write('$$\r\n')
        title_flag = False
    
def getFatherInfoBycode(code):
    contents = db.GqlQuery("SELECT * FROM ContentClass WHERE code = :1 AND status='1'", code).fetch(1)
    con=[]
    for c in contents:
        if c.father!='' or c.father!=None:
            con+=getAllInfoByFather(c.father)
    return contents+con

    
    ##输出其他子层资讯


    
                        
#资讯更新接口
#http://localhost:8084/InfoUpdate?UserName=f123456&AllLastUpdateTime=2010-09-1011:28:33&MainCode:LastUpdateTime=a6:2010-09-1011:28:33






    
   
      

#更加编号查看是第几层
def getCodeLength(code):
    codelist = code.split('-')
    layer = len(codelist)
    return layer

def isReplyContent(self,code):
    if code.find('s')== -1:
        contents = db.GqlQuery("SELECT * FROM ContentClass WHERE code=:1",code)
        for content in contents:
            if content.content:
                self.response.out.write('$$'+content.content.encode('utf-8'))
    else:
        replyContents = db.GqlQuery("SELECT * FROM ReplyContent WHERE code=:1",code)
        for replyContent in replyContents:
            if replyContent.content:
                self.response.out.write('$$'+replyContent.content.encode('utf-8'))
                self.response.out.write('$$'+replyContent.replyType.encode('utf-8'))#特殊节点的回复类型

def isReplyContent_Update(self,code):
    if code.find('s')== -1:
        contents = db.GqlQuery("SELECT * FROM ContentClass WHERE code=:1",code)
        for content in contents:
            self.response.out.write('$$'+content.content.encode('utf-8'))
            self.response.out.write('$$'+content.status.encode('utf-8')+'\r\n')
    else:
        replyContents = db.GqlQuery("SELECT * FROM ReplyContent WHERE code=:1",code)
        for replyContent in replyContents:
            self.response.out.write('$$'+replyContent.content.encode('utf-8'))
            self.response.out.write('$$'+content.status.encode('utf-8')+'\r\n')

#//获取当前时间类
#//获取当前时间类
def getCurrentTime():
    try:
        dt=datetime.datetime.now()
        ss=str(dt.year)+'-'
        if dt.month>10:
            ss+=str(dt.month)
        else:
            ss+='0'+str(dt.month)
        if dt.day>10:
            ss+='-'+str(dt.day)
        else:
            ss+='-0'+str(dt.day)
        if dt.hour>10:
            ss+=' '+str(dt.hour)
        else:
            ss+=' 0'+str(dt.hour)
        if dt.minute>10:
            ss+=':'+str(dt.minute)
        else:
            ss+=':0'+str(dt.minute)
        if dt.second>10:
            ss+=':'+str(dt.second)
        else:
            ss+=':0'+str(dt.second)
        return datetime.datetime.strptime(ss,'%Y-%m-%d %H:%M:%S')
    except:
        return datetime.datetime.now()


    
  






  


#//通过时间查询其它层的特殊节点编号集合





  


#2010年5月18日增加
#资讯更新接口http://localhost:8084/InfoUpdate?UserName=f123456&AllLastUpdateTime=2010-08-1011:28:33&MainCode:LastUpdateTime=a6:2010-08-1011:28:33


